package com.forlove.app.qselect;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;

import com.forlove.app.ForloveApplication;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.base.ui.BaseFragment;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.utils.SystemUtils;
import com.forlove.app.event.ActiveFlagEvent;
import com.forlove.app.event.EventEntity;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.UpdateUserinfoAsync;
import com.forlove.app.qselect.answer.ui.AnswerSubjectActivity;
import com.forlove.app.qselect.answer.ui.CircleGuideActivity;
import com.forlove.app.qselect.friend.ui.AddFriendGuideActivity;
import com.forlove.app.qselect.friend.ui.MineNewFriendFragment;
import com.forlove.app.qselect.friend.ui.SearchUserInfoActivity;
import com.forlove.app.qselect.index.ui.FriendCircleInfoFragment;
import com.forlove.app.qselect.index.ui.IndexFragment;
import com.forlove.app.qselect.index.ui.MineCircleInfoFragment;
import com.forlove.app.qselect.index.ui.MineInfoActivity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.ui.LimitAreaActivity;
import com.forlove.app.qselect.login.ui.SetUserInfoActivity;
import com.forlove.app.qselect.update.diaolog.FileDownloadDialog;
import com.forlove.app.qselect.update.entity.UpdateEntity;
import com.forlove.app.qselect.update.presenter.UpdataPresenter;
import com.forlove.app.qselect.update.view.MainView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import cn.magicwindow.MLinkAPIFactory;

/**
 * Created by yjl on 2017/9/27.
 */

public class MainActivity extends BaseActivity implements MainTabView.MainTabClickListener,
        LoaderManager.LoaderCallbacks<UserEntity>, MainView, MainTabView.ActiveFlagListener {
    public final static int POSITION_INDEX = 0; //首页
    public final static int POSITION_FRIEND = 1;//好友

    public static final String Key_Comefrom = "come_from";//从哪过来

    public static final int COME_FROM_REGISTER = 1;//从注册页面过来

    public static final int COME_FROM_ADD_FRIEND_GUIDE = 2;//从添加好友页面

    public static final int COME_TO_CIRCLE = 3;//跳转到圈一圈

    public static final int COME_TO_WEB = 4;//从网页打开app

    public static final int COME_FROM_WELCOME = 5;//打开app

    public static int unread_num = 0;//未读被圈消息数
    public static int undealwith_request = 0;//未处理好友请求数
    @BindView(R.id.tab_main)
    MainTabView tab_main;  //tabview

    @BindView(R.id.image_circle_friend)
    ImageView image_circle_friend;

    private FragmentManager fragmentManager;
    private ArrayList<BaseFragment> fragmentList = new ArrayList<>();
    private static int mCurrentPosition = POSITION_INDEX;  //当前位置
    private UpdateUserinfoAsync updateUserinfoAsync;
    //    private MineFriendFragment mineFriendFragment;
    private MineNewFriendFragment mineNewFriendFragment;
    private IndexFragment indexFragment;
    private UpdataPresenter updataPresenter;
    private FileDownloadDialog fileDownloadDialog; //下载进度的dialog
    private int comeFrom = -1;//来自哪
    private boolean isRequestUpdate = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    public static int getCurrentPosition() {

        return mCurrentPosition;
    }

    private void initPos() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            int pos = bundle.getInt("position", -1);
            if (pos > -1) {
                mCurrentPosition = pos;
            }
            int childView = bundle.getInt("childView", -1);
            if (childView > -1 && childView != IndexFragment.getPos()) {
                IndexFragment.setPos(childView);
            }
            comeFrom = bundle.getInt(Key_Comefrom);
            if (comeFrom == COME_FROM_REGISTER) {
                FriendManager.saveFirstOpenCircle(MainActivity.this, false);
                getIntent().setClass(this, AddFriendGuideActivity.class);
                startActivity(getIntent());
            } else if (comeFrom == COME_FROM_ADD_FRIEND_GUIDE) {
                FriendManager.saveFirstOpenCircle(MainActivity.this, false);
                startActivity(new Intent(MainActivity.this, AnswerSubjectActivity.class));
            } else if (comeFrom == COME_TO_CIRCLE) {
                //推送跳转到答题页
                if (FriendManager.getFirstOpenCircle(MainActivity.this)) {
                    FriendManager.saveFirstOpenCircle(MainActivity.this, false);
                    startActivity(new Intent(MainActivity.this, CircleGuideActivity.class));
                } else {
                    startActivity(new Intent(MainActivity.this, AnswerSubjectActivity.class));
                }
            } else if (comeFrom == COME_TO_WEB) {
                //从应用宝或者微信web页打开
                String mobile = bundle.getString("mobile");
                if (StringUtils.isNotEmpty(mobile) && StringUtils.isMobile(mobile)) {
                    UserEntity userEntity = UserManager.getUesrInfo(this);
                    if (!mobile.equals(userEntity.userMobile)) {
                        Intent intent = new Intent(this, SearchUserInfoActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(this, MineInfoActivity.class);
                        startActivity(intent);
                    }
                }
            } else if (comeFrom == COME_FROM_WELCOME) {
                //推送跳转到答题页
                if (FriendManager.getFirstOpenCircle(MainActivity.this)) {
                    FriendManager.saveFirstOpenCircle(MainActivity.this, false);
                    startActivity(new Intent(MainActivity.this, CircleGuideActivity.class));
                } else {
                    startActivity(new Intent(MainActivity.this, AnswerSubjectActivity.class));
                }
            }

        }
    }

    @Override
    public void initView() {
        MLinkAPIFactory.createAPI(this).deferredRouter();
        initPos();
        fragmentManager = getSupportFragmentManager();
        updataPresenter = new UpdataPresenter(this);
        initFragment();
        tab_main.setMainTabClickListener(this);
        image_circle_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FriendManager.getFirstOpenCircle(MainActivity.this)) {
                    FriendManager.saveFirstOpenCircle(MainActivity.this, false);
                    startActivity(new Intent(MainActivity.this, CircleGuideActivity.class));
                } else {
                    startActivity(new Intent(MainActivity.this, AnswerSubjectActivity.class));
                }
            }
        });
        checkUserInfo();
        getSupportLoaderManager().restartLoader(UpdateUserinfoAsync.ASYNC_ID, null, this);

        //TODO 请求更新
        if (!isRequestUpdate) {
            updataPresenter.update(SystemUtils.getAppVersionName(this));
        }
    }

    private void initFragment() {
        if (fragmentList.size() == 0) {
            fragmentList.clear();
            FragmentTransaction ft = fragmentManager.beginTransaction();
            indexFragment = new IndexFragment();
            fragmentList.add(POSITION_INDEX, indexFragment);
            ft.add(R.id.view_main, indexFragment, "POSITION_INDEX");
//            mineFriendFragment = new MineFriendFragment();
            mineNewFriendFragment = new MineNewFriendFragment();
            fragmentList.add(POSITION_FRIEND, mineNewFriendFragment);
            ft.add(R.id.view_main, mineNewFriendFragment, "POSITION_FRIEND");
            //TODO 处理切换登陆后白屏问题
            for (int i = 0; i < fragmentList.size(); i++) {
                BaseFragment baseFragment = fragmentList.get(i);
                if (i == mCurrentPosition) {
                    ft.show(baseFragment);
                    baseFragment.onSelected(mCurrentPosition);
                } else {
                    ft.hide(baseFragment);
                }
            }
            ft.commitAllowingStateLoss();
            changeTabStatus(mCurrentPosition);
            FriendCircleInfoFragment.setActiveFlagListener(this);
            MineCircleInfoFragment.setActiveFlagListener(this);
        }
    }


    private void updateFragmentView(int pos) {
        if (fragmentManager == null) {
            fragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction ft = fragmentManager.beginTransaction();
        switch (pos) {
            case POSITION_INDEX:
                if (indexFragment == null) {
                    indexFragment = (IndexFragment) fragmentManager.findFragmentByTag("POSITION_INDEX");
                }
                tab_main.hideHasFriend();
                ft.show(indexFragment).hide(fragmentList.get(POSITION_FRIEND));
                break;
            case POSITION_FRIEND:
                if (mineNewFriendFragment == null) {
                    mineNewFriendFragment = (MineNewFriendFragment) fragmentManager.findFragmentByTag("POSITION_FRIEND");
                }
                ft.show(mineNewFriendFragment).hide(fragmentList.get(POSITION_INDEX));
                break;
        }
        ft.commitAllowingStateLoss();
        mCurrentPosition = pos;
        fragmentList.get(pos).onSelected(pos);
    }

    private void changeTabStatus(int pos) {
        switch (pos) {
            case POSITION_INDEX:
                tab_main.showIndex();
                break;
            case POSITION_FRIEND:
                tab_main.showFriend();
                break;
        }
    }

    @Override
    public void OnTabSelected(final int pos) {
        if (pos == mCurrentPosition) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (pos == POSITION_FRIEND) {
                    tab_main.hideHasFriend();
                }
                updateFragmentView(pos);
            }
        });

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        LogUtil.e("yjl", "mainactiviry  onNewIntent");
        initPos();
        changeTabStatus(mCurrentPosition);
        updateFragmentView(mCurrentPosition);

    }

    private void checkUserInfo() {
        if (!UserManager.getUserLoginState(this)) {
            return;
        }
        UserEntity userEntity = UserManager.getUesrInfo(this);
        if (!StringUtils.isNotEmpty(userEntity.realname)) {
            Intent intent = new Intent(this, SetUserInfoActivity.class);
            startActivity(intent);
        }

    }

    private long deltTime = 0;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - deltTime > 2000) {
            deltTime = System.currentTimeMillis();
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            return;
        }
        super.onBackPressed();
        ForloveApplication.getInstance().exit();
    }

    @Override
    protected void onDestroy() {
        if (fragmentList != null && fragmentList.size() > 0) {
            fragmentList.clear();
        }
        getSupportLoaderManager().destroyLoader(UpdateUserinfoAsync.ASYNC_ID);
        if (updateUserinfoAsync != null) {
            updateUserinfoAsync.cancelLoad();
            updateUserinfoAsync = null;
        }

        if (fileDownloadDialog != null) {
            fileDownloadDialog.dismiss();
            fileDownloadDialog = null;
        }
        super.onDestroy();

    }

    private UpdateUserinfoAsync createAsync() {
        if (updateUserinfoAsync == null) {
            updateUserinfoAsync = new UpdateUserinfoAsync(this);
        }
        return updateUserinfoAsync;
    }

    @Override
    public Loader<UserEntity> onCreateLoader(int id, Bundle args) {
        return createAsync();
    }

    @Override
    public void onLoadFinished(Loader<UserEntity> loader, UserEntity data) {
        //TODO 如果不需要每次回到主界面都获取最新的消息情况就注释掉
//        if (updateUserinfoAsync != null) {
//            updateUserinfoAsync.cancelLoadInBackground();
//            updateUserinfoAsync.cancelLoad();
//            getSupportLoaderManager().destroyLoader(UpdateUserinfoAsync.ASYNC_ID);
//        }
    }

    @Override
    public void onLoaderReset(Loader<UserEntity> loader) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
    public void onEventMainThread(EventEntity event) {
        super.onEventMainThread(event);
        LogUtil.e("yjl", "event id:" + event.eventId + "   evien name:" + event.eventName);
        if (event != null && event.eventId == EventManager.EVENT_NEW_FLAG) {
            long oldAddtime = FriendManager.getNewFriendAddTime(this);
            if (event instanceof ActiveFlagEvent) {
                ActiveFlagEvent activeFlagEvent = (ActiveFlagEvent) event;
                MineCircleInfoFragment.unReadNum = activeFlagEvent.unread;
                unread_num = activeFlagEvent.unread;
                undealwith_request = activeFlagEvent.requestCount;
                if (activeFlagEvent.newFAddtime > oldAddtime) {
                    tab_main.showHasFriend();
                } else {
                    tab_main.hideHasFriend();
                }

                if (MineCircleInfoFragment.unReadNum > 0) {
                    tab_main.showHasUnRead(MineCircleInfoFragment.unReadNum);
                } else {
                    int oldId = UserManager.getNewCircleInfo(this);
                    if (activeFlagEvent.lastRecord > oldId) {
                        tab_main.showHasNewCircle();
                    } else {
                        tab_main.hideHasNewCircle();
                        tab_main.hideHasUnread();
                    }
                }
            }

        } else if (event != null && event.eventId == EventManager.EVENT_LIMIT_LOGIN) {
            if (NetworkUtils.instance(this).isNetworkAvailable()) {
                Intent intent = new Intent(this, LimitAreaActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            } else {
                Toast.makeText(this, "请检查网络！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void showDownloadDialog(final UpdateEntity updateEntity) {
        isRequestUpdate = true;
        if (updateEntity != null
                && updateEntity.getStatus() == 200
                && updateEntity.getVesion() > Float.valueOf(SystemUtils.getAppVersionName(this))) {

            if (fileDownloadDialog == null) {
                fileDownloadDialog = new FileDownloadDialog(MainActivity.this, updateEntity);
            } else {
                fileDownloadDialog.setUpdateEntity(updateEntity);
            }
            fileDownloadDialog.setcancel(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (fileDownloadDialog.isShowing()) {
                        fileDownloadDialog.dismiss();
                        setBackGround(1f);
                    }
                }
            });
            if (!fileDownloadDialog.isShowing()) {
                fileDownloadDialog.show(false);
                setBackGround(0.6f);
            }
        }

    }

    public void setBackGround(float fot) {
        WindowManager.LayoutParams layout = getWindow().getAttributes();
        float params = layout.alpha = fot;//屏幕亮度变暗
        getWindow().setAttributes(layout);
    }

    @Override
    public void readMineCircle(int unread) {
        if (unread > 0) {
            tab_main.showHasUnRead(unread);
        } else {
            tab_main.hideHasUnread();
        }
    }

    @Override
    public void readFriendCircleInfo(boolean isShow) {
        if (!isShow) {
            tab_main.hideHasNewCircle();
        } else {
            tab_main.showHasNewCircle();
        }
    }

    @Override
    public void readNewFriendInfo(boolean isShow) {
        if (!isShow) {
            tab_main.hideHasFriend();
        } else {
            tab_main.showHasFriend();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (fragmentList.size() > 0) {
            fragmentList.get(mCurrentPosition).onActivityResult(requestCode, resultCode, data);
        }
    }

}
